package com.archermind.style.controller;

import com.alibaba.fastjson.JSONObject;
import com.archermind.style.bean.Attachment;
import com.archermind.style.bean.AttachmentFolder;
import com.archermind.style.interceptor.Auth;
import com.archermind.style.service.AttachmentService;
import com.archermind.style.util.Result;
import com.archermind.style.util.Search;
import com.archermind.style.util.SessionUtil;
import com.feng.fengDUtil.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * ["查看附件","编辑附件","下载附件"]
 */
@RestController
@RequestMapping(value = "/attachment")
@Auth("查看附件")
public class AttachmentAction {

    @Autowired
    private AttachmentService attachmentService;

    @RequestMapping(value = "/list")
    public Result list( Page page,Search search) {
        attachmentService.query(page,search);
        return Result.success(page);
    }

    @Auth("编辑附件")
    @RequestMapping(value="/del")
    public Result del(String ids){
        try {
            attachmentService.del(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/listFolders")
    public Result listFolders(String folder) {
        List<AttachmentFolder> list = attachmentService.listFolders(folder);
        return Result.success(list);
    }

    @Auth("编辑附件")
    @RequestMapping(value="/saveFolder")
    public Result saveFolder(@RequestBody AttachmentFolder folder){
        try {
            attachmentService.saveOrUpdate(folder);
            return Result.success(folder);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/existFile")
    public Result existFile( Integer folderId) {
        Long exists = attachmentService.sql("select 1 from attachment where folderId = ? limit 1").one(Long.class,folderId);
        return Result.success(exists);
    }

    @Auth("编辑附件")
    @RequestMapping(value="/delFolder")
    public Result delFolder(Integer folderId){
        try {
            attachmentService.deleteById(AttachmentFolder.class,folderId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Auth("编辑附件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Result uploadFile(HttpServletRequest request,Integer folderId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
        JSONObject data = new JSONObject();
        List<Attachment> items = new ArrayList();
        List<String> names = new ArrayList<>();
        try {
            //循环获取file数组中得文件
            for(Map.Entry<String, List<MultipartFile>> entity:fileMap.entrySet()){
                List <MultipartFile> files = entity.getValue();
                for(MultipartFile file:files){
                    Attachment item = new Attachment();
                    String name = file.getOriginalFilename();
                    item.setName(name);
                    item.setCreateTime(new Date());
                    item.setCreator(SessionUtil.getCurUserId());
                    names.add(name);
                    item.setSize(new Long(file.getSize()/1000).intValue());
                    item.setPath(attachmentService.saveAttachment(file));
                    item.setFolderId(folderId);
                    items.add(item);
                }
            }
            List<Attachment> existsFiles = attachmentService.selectExistsFiles(folderId,names);
            if(existsFiles.size()>0){
                List<Integer> idList = new ArrayList<>();
                for(Attachment file:existsFiles){
                    idList.add(file.getId());
                }
                attachmentService.del(StringUtils.collectionToCommaDelimitedString(idList));
                data.put("deleteIds",idList);
            }
            attachmentService.saveOrUpdateAll(items);
            data.put("files",items);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @Auth("下载附件")
    @RequestMapping(value = "/downloadZip", method = RequestMethod.GET)
    public void downloadZip(HttpServletResponse httpServletResponse, @RequestParam("ids") String ids) throws IOException {
        httpServletResponse.setContentType("application/zip");
        httpServletResponse.setHeader("Content-disposition",
                "attachment; filename=" + new String("attachments".getBytes(),"ISO-8859-1") + ".zip");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

        List<Attachment> items = attachmentService.getByIds(ids);
        int count;
        byte[] buf = new byte[1024];
        for(Attachment item:items){
            File file = attachmentService.getFile(item);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            zipOutputStream.putNextEntry(new ZipEntry(item.getName()));
            //将源文件写入到zip文件中
            while((count=bis.read(buf))!=-1)
            {
                zipOutputStream.write(buf,0,count);
            }
            bis.close();
        }

        zipOutputStream.flush();
        zipOutputStream.close();

        outputStream.flush();
        outputStream.close();
    }


}